package com.lhz.project.system.service.auth.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhz.common.constant.AccountTypeConstant;
import com.lhz.common.constant.DataStatusEnum;
import com.lhz.common.constant.ResponseState;
import com.lhz.common.page.BaseQueryParam;
import com.lhz.common.page.NewPageBean;
import com.lhz.common.utils.MD5Utils;
import com.lhz.common.utils.UUIDUtils;
import com.lhz.framework.aspect.param.DataScope;
import com.lhz.framework.security.HolderInfoManager;
import com.lhz.project.system.mapper.auth.LoginMapper;
import com.lhz.project.system.mapper.auth.RoleMapper;
import com.lhz.project.system.mapper.auth.UserMapper;
import com.lhz.project.system.mapper.auth.UserRoleMapper;
import com.lhz.project.system.model.entity.auth.Account;
import com.lhz.project.system.model.entity.auth.Role;
import com.lhz.project.system.model.entity.auth.User;
import com.lhz.project.system.model.entity.auth.UserRole;
import com.lhz.project.system.model.param.base.UserParam;
import com.lhz.project.system.model.vo.auth.UserRoleVo;
import com.lhz.project.system.service.auth.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LiHuaZhi
 * @since 2020-06-12 22:30:48
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private LoginMapper loginMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public User selectByPrimaryKey(String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    @DataScope(userAlias = "a", deptAlias = "b")
    public Object listUser(BaseQueryParam param) {
        log.info("======== INFO ======== ");
        log.debug("======== DEBUG ======== ");
        log.error("======== error ======== ");
        //分页
        return NewPageBean.generatePage(() -> userMapper.listUser(param), param, User.class);
    }

    @Override
    @Transactional
    public int insert(UserParam param) {
        //判断用户名是否存在
        checkUser(param.getUsername());

        String userId = HolderInfoManager.getUserId();
        User user = new User();
        BeanUtils.copyProperties(param, user);

        user.setId(UUIDUtils.getUuId());
        user.setType(AccountTypeConstant.USER);
        user.setStatus(DataStatusEnum.VALID.getCode());
        user.setDelFlag(DataStatusEnum.VALID.getCode());
        user.setCreateBy(userId);
        user.setUpdateBy(userId);

        //设置账户信息
        Account account = new Account();
        account.setId(UUIDUtils.getUuId());
        account.setUserId(user.getId());
        account.setUsername(param.getUsername());
        //密码加密
        String password = MD5Utils.getSaltMd5(param.getPassword());
        account.setPassword(password);
        account.setStatus(DataStatusEnum.VALID.getCode());
        account.setCreateBy(userId);
        account.setUpdateBy(userId);

        userMapper.insertAccount(account);

        // 新增用户与角色管理
        insertUserRole(user.getId(), param.getRoleIds());

        return userMapper.insert(user);
    }

    @Override
    @Transactional
    public int updateByPrimaryKey(UserParam param) {
        String userId = HolderInfoManager.getUserId();
        User user = new User();
        BeanUtils.copyProperties(param, user);

        //删除原来关联角色
        userRoleMapper.deleteRoleByUserId(user.getId());

        // 新增用户与角色管理
        insertUserRole(user.getId(), param.getRoleIds());

        user.setUpdateBy(userId);
        return userMapper.updateById(user);
    }

    @Override
    @Transactional
    public int deletePhyByPrimaryKey(String id) {
        //删除原来关联角色
        userRoleMapper.deleteRoleByUserId(id);
        //删除账户
        userMapper.deletePhyAccountByPrimaryKey(id);
        return userMapper.deletePhyByPrimaryKey(id);
    }

    @Override
    public int deletePhyByPrimaryKeys(List<String> ids) {
        //批量删除原来关联角色
        userRoleMapper.deleteRoleByUserIds(ids);

        //删除账户
        userMapper.deletePhyAccountByPrimaryKeys(ids);
        return userMapper.deletePhyByPrimaryKeys(ids);

    }

    //查询用户-角色分配
    @Override
    public Object getUserRole(String userId) {
        //获取分配的角色
        List<Role> roles = userRoleMapper.selectRolesByUserId(userId);
        List<Integer> roleIds = roles.stream().map(Role::getId).collect(Collectors.toList());

        //查询所有角色列表
        List<Role> roleList = roleMapper.listAll();

        UserRoleVo roleVo = new UserRoleVo();
        roleVo.setRoleIds(roleIds);
        roleVo.setRoleList(roleList);
        return roleVo;
    }

    /**
     * 检查用户名是否存在
     */
    private void checkUser(String userName) {
        Account account = loginMapper.getAccount(userName);
        Assert.isNull(account, ResponseState.ACCOUNT_DEFINED.name());
    }

    private void insertUserRole(String userId, List<Integer> roleIds) {
        List<UserRole> list = new ArrayList<>();
        for (Integer roleId : roleIds) {
            UserRole ur = new UserRole();
            ur.setRoleId(roleId);
            ur.setUserId(userId);
            list.add(ur);
        }
        if (CollectionUtil.isNotEmpty(list)) {
            userRoleMapper.insertBatch(list);
        }
    }
}